package com.lengyu.vxminiprogram.security;


import com.alibaba.fastjson.JSONObject;
import com.lengyu.vxminiprogram.entity.Role;
import com.lengyu.vxminiprogram.security.rest.dto.JwtUser;
import com.lengyu.vxminiprogram.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.io.Serializable;
import java.util.Collection;


@Configuration
public class CustomPermissionEvaluator implements PermissionEvaluator {
    @Autowired
    private IRoleService roleService;

    @Override
    public boolean hasPermission(Authentication authentication, Object targetUrl, Object permission) {
        String jwtUserStr = String.valueOf(authentication.getPrincipal());
        // 获得loadUserByUsername()方法的结果
        JwtUser jwtUser = JSONObject.toJavaObject(JSONObject.parseObject(jwtUserStr),JwtUser.class);
        // 获得用户授权
        Collection<GrantedAuthority> authorities = jwtUser.getAuthorities();

        // 遍历用户所有角色
        for(GrantedAuthority authority : authorities) {
            String roleCode = authority.getAuthority();
            if(roleCode.equals("admin")){
                return true;
            }
            Role role = roleService.getByCode(roleCode);
            String roleId;
            if(role != null){
                roleId = role.getId();
            }
            else{
                continue;
            }
//            RoleWithMenuView roleWithMenuView =  roleWithMenuViewService.getById(roleId);
//            RoleWithMenuViewDto menuDto = roleWithMenuViewConverter.entityToDto(roleWithMenuView);
//            // 得到角色所有的权限
//            List<String> permissionList = menuDto.getPermissions();
//            if (null == permissionList) {
//                continue;
//            }

//            // 遍历permissionList
//            for(String permisson : permissionList) {
//                String pstr = permisson;
//                // 判空
//                if (StringUtils.isBlank(pstr)) {
//                    continue;
//                }
//                // 如果访问的url和权限相符，返回true
//                if (pstr.equals(permission)) {
//                    return true;
//                }
//            }

            return true;
        }

        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable,
            String targetUrl, Object permission) {
        return false;
    }
}
